<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      .box {
        height: 150px;
        width: 150px;
        border-radius: 50%;
        background-color: rgb(102, 47, 165);
        position: absolute;
        top: 10px;
        left: 10px;
        cursor: move;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
  </body>
</html>
<script>
  // 元素的拖拽
  var box = document.querySelector(".box");
  box.onmousedown = function (e) {
    var e = e || window.event;
    // 找到每次鼠标点击元素 鼠标距离元素左上角的距离
    // clientX clientY 鼠标点击位置距离浏览器左上角的距离
    // offsetLeft offsetTop 元素距离浏览器左上角的距离
    var x = e.clientX - this.offsetLeft;
    var y = e.clientY - this.offsetTop;
    window.onmousemove = function (e) {
      var ev = e || event;
      box.style.left = ev.clientX - x + "px";
      box.style.top = ev.clientY - y + "px";
    };
  };
  window.onmouseup = function () {
    window.onmousemove = null;
  };
</script>
